package com.moyun.modelclass.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.moyun.modelclass.adapter.HomeFindAdapter;
import com.moyun.modelclass.adapter.RelatedUsersAdapter;
import com.moyun.modelclass.adapter.SearchResultAdapter;
import com.moyun.modelclass.base.BaseActivity;
import com.moyun.modelclass.dialog.ScanImageDialog;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.CheckCollectListUserApi;
import com.moyun.modelclass.http.api.CheckFollowListUserApi;
import com.moyun.modelclass.http.api.CollectArticleApi;
import com.moyun.modelclass.http.api.FollowUserApi;
import com.moyun.modelclass.http.api.HomeFindApi;
import com.moyun.modelclass.http.api.UserSearchApi;
import com.moyun.modelclass.http.bean.ArticleResponse;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.utils.StatusBarUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Meteor
 * tip：搜索结果
 */
public class SearchResultActivity extends BaseActivity implements SearchResultAdapter.OnFindClick {
    private RelativeLayout llSearchResultTop;
    private ImageView ivSearchResultBack;
    private TextView tvSearchResultCheck;
    private RecyclerView recyclerSearchResultRelated;
    private TextView tvSearchResultOne;
    private TextView tvSearchResultTwo;
    private TextView tvSearchResultThree;
    private SmartRefreshLayout searchResultRefresh;
    private RecyclerView recyclerSearchResult;

    private RelatedUsersAdapter relatedUsersAdapter = new RelatedUsersAdapter();
    private SearchResultAdapter searchResultAdapter = new SearchResultAdapter();
    private String searchInfo = "";//搜索词
    private String mLastId = "";

    private int mSortType = 1;//排序方式,1、默认 2、热度 3、发布日期

    private List<String> userIdList = new ArrayList<>();
    private List<String> articleIdList = new ArrayList<>();


    public static void start(Context context, String search) {
        Intent starter = new Intent(context, SearchResultActivity.class);
        starter.putExtra("searchInfo", search);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_search_result;
    }

    @Override
    protected void assignViews() {
        llSearchResultTop = (RelativeLayout) findViewById(R.id.ll_search_result_top);
        ivSearchResultBack = (ImageView) findViewById(R.id.iv_search_result_back);
        tvSearchResultCheck = (TextView) findViewById(R.id.tv_search_result_check);
        searchResultRefresh = (SmartRefreshLayout) findViewById(R.id.search_result_refresh);
        recyclerSearchResultRelated = (RecyclerView) findViewById(R.id.recycler_search_result_related);
        tvSearchResultOne = (TextView) findViewById(R.id.tv_search_result_one);
        tvSearchResultTwo = (TextView) findViewById(R.id.tv_search_result_two);
        tvSearchResultThree = (TextView) findViewById(R.id.tv_search_result_three);
        recyclerSearchResult = (RecyclerView) findViewById(R.id.recycler_search_result);

        StatusBarUtil.setPaddingSmart(this, llSearchResultTop);

        recyclerSearchResultRelated.setLayoutManager(new GridLayoutManager(mContext, 4));
        recyclerSearchResultRelated.setAdapter(relatedUsersAdapter);

        recyclerSearchResult.setLayoutManager(new LinearLayoutManager(mContext));
        searchResultAdapter.setOnFindClick(this);
        recyclerSearchResult.setAdapter(searchResultAdapter);
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(ivSearchResultBack, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        ClickUtils.applySingleDebouncing(tvSearchResultCheck, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //查看全部
                RelatedUsersAllActivity.start(SearchResultActivity.this, searchInfo);
            }
        });

        //综合
        ClickUtils.applySingleDebouncing(tvSearchResultOne, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSortType = 1;
                tvSearchResultOne.setTextColor(Color.parseColor("#055D6C"));
                tvSearchResultTwo.setTextColor(Color.parseColor("#767676"));
                tvSearchResultThree.setTextColor(Color.parseColor("#767676"));
                initAppSearchLog(true);
            }
        });

        //热度排序
        ClickUtils.applySingleDebouncing(tvSearchResultTwo, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSortType = 2;
                tvSearchResultOne.setTextColor(Color.parseColor("#767676"));
                tvSearchResultTwo.setTextColor(Color.parseColor("#055D6C"));
                tvSearchResultThree.setTextColor(Color.parseColor("#767676"));
                initAppSearchLog(true);
            }
        });

        //发布日期排序
        ClickUtils.applySingleDebouncing(tvSearchResultThree, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSortType = 3;
                tvSearchResultOne.setTextColor(Color.parseColor("#767676"));
                tvSearchResultTwo.setTextColor(Color.parseColor("#767676"));
                tvSearchResultThree.setTextColor(Color.parseColor("#055D6C"));
                initAppSearchLog(true);
            }
        });

        searchResultRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mLastId = "";
                userIdList.clear();
                articleIdList.clear();
                initAppSearchLog(true);
            }
        });
        searchResultRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                initAppSearchLog(false);
            }
        });
    }

    @Override
    protected void getExtras(Bundle bundle) {
        searchInfo = bundle.getString("searchInfo", "");
    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        initRelatedUsersLog();
        initAppSearchLog(true);
    }

    private void initRelatedUsersLog() {
        EasyHttp.post(this)
                .api(new UserSearchApi().setLastId("").setPageSize(3).setSearchText(searchInfo))
                .request(new HttpCallback<HttpData<UserSearchApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<UserSearchApi.Bean> result) {
                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            relatedUsersAdapter.setList(result.getData().getList());
                        } else {
                            relatedUsersAdapter.setList(new ArrayList<>());
                            relatedUsersAdapter.setEmptyView(R.layout.empty_view_layout);
                        }
                    }
                });
    }

    private void initAppSearchLog(boolean isRefresh) {
        mLastId = isRefresh ? "" : mLastId;
        EasyHttp.post(this)
                .api(new HomeFindApi().setLastId(mLastId).setPageSize(CommonConfiguration.page).setSearchText(searchInfo).setAuthorUserId("").setSortType(mSortType))
                .request(new HttpCallback<HttpData<HomeFindApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<HomeFindApi.Bean> result) {
                        searchResultRefresh.finishRefresh();
                        searchResultRefresh.finishLoadMore();
                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            mLastId = result.getData().getList().get(result.getData().getList().size() - 1).getId();
                            if (isRefresh) {
                                searchResultAdapter.setList(result.getData().getList());
                            } else {
                                searchResultAdapter.addData(result.getData().getList());
                            }
                        } else {
                            if (isRefresh) {
                                searchResultAdapter.setList(new ArrayList<>());
                                searchResultAdapter.setEmptyView(R.layout.empty_view_layout);
                            }
                        }

                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            for (ArticleResponse item : result.getData().getList()) {
                                userIdList.add(item.getCreateUser());
                                articleIdList.add(item.getId());
                            }
                        }
                        checkUserListFollow();
                        checkUserListCollect();
                    }
                });
    }

    private void checkUserListFollow() {
        if (CommonConfiguration.isLogin(kv)) {
            EasyHttp.post(this)
                    .api(new CheckFollowListUserApi().setUserIdList(userIdList))
                    .request(new HttpCallback<HttpData<CheckFollowListUserApi.Bean>>(this) {
                        @Override
                        public void onSucceed(HttpData<CheckFollowListUserApi.Bean> result) {
                            if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                                searchResultAdapter.setFollowState(result.getData().getList());
                            }
                        }
                    });
        }
    }

    private void checkUserListCollect() {
        if (CommonConfiguration.isLogin(kv)) {
            EasyHttp.post(this)
                    .api(new CheckCollectListUserApi().setArticleIdList(articleIdList))
                    .request(new HttpCallback<HttpData<CheckCollectListUserApi.Bean>>(this) {
                        @Override
                        public void onSucceed(HttpData<CheckCollectListUserApi.Bean> result) {
                            if (result != null && result.getData() != null && result.getData().getLikes().size() > 0) {
                                searchResultAdapter.setArticleState(result.getData().getLikes());
                            }
                        }
                    });
        }
    }

    @Override
    public void userInfo(String userId) {
        UserInfoActivity.start(SearchResultActivity.this, userId);
    }

    @Override
    public void details(String articleId) {
        ArticleDetailsActivity.start(this, articleId,false);
    }

    @Override
    public void imageUrl(String url) {
        ScanImageDialog.getInstance(this, url).builder().setNegativeButton().show();
    }

    @Override
    public void follow(String userId, boolean isFollow) {
        EasyHttp.post(this)
                .api(new FollowUserApi().setUserId(userId).setFollow(isFollow))
                .request(new HttpCallback<HttpData<FollowUserApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<FollowUserApi.Bean> result) {
                        checkUserListFollow();
                        if (isFollow) {
                            ToastUtils.showShort("已关注");
                        } else {
                            ToastUtils.showShort("取消关注");
                        }
                    }
                });
    }

    @Override
    public void collect(String articleId, boolean isCollect) {
        EasyHttp.post(this)
                .api(new CollectArticleApi().setArticleId(articleId).setLikes(isCollect))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
//                        checkUserListCollect();
                        if (isCollect) {
                            ToastUtils.showShort("已收藏");
                        } else {
                            ToastUtils.showShort("取消收藏");
                        }
                    }
                });
    }
}
